<template>
  <n-layout has-sider>
    <!-- 侧边菜单（仅桌面端显示） -->
    <n-layout-sider
      v-if="!isMobile"
      :width="240"
      :collapsed="sidebarCollapsed"
      :collapsed-width="64"
      collapse-mode="width"
      show-trigger="arrow-circle"
      @collapse="sidebarCollapsed = true; saveSidebarState()"
      @expand="sidebarCollapsed = false; saveSidebarState()"
    >
      <!-- 侧边导航菜单 -->
      <n-menu
        :value="activeKey"
        :options="sideMenuOptions"
        @update:value="handleMenuUpdate"
        :collapsed="sidebarCollapsed"
        :collapsed-width="64"
        :collapsed-icon-size="22"
        :root-props="{ style: 'background: transparent; border: none;' }"
      />
    </n-layout-sider>
    <!-- 内层布局，包含顶部导航 / 内容 / Footer -->
    <n-layout>
      <n-layout-header class="app-header" bordered>
        <nav class="nav-container">
          <!-- Logo 品牌区域 -->
          <div class="brand-section" @click="router.push('/')">
            <n-avatar :size="40" :src="logoUrl" class="brand-logo" color="transparent">
              <template #fallback>
                <n-icon :size="24">
                  <HomeOutline />
                </n-icon>
              </template>
            </n-avatar>
            <div class="brand-text">
              <h1 class="brand-title">三角洲数据查询攻略站</h1>
              <span class="brand-subtitle">Operation Delta</span>
            </div>
          </div>

          <!-- 桌面端导航菜单 -->
          <div v-if="!isMobile" class="nav-menu">
            <n-menu :value="activeKey" mode="horizontal" :options="menuOptions" @update:value="handleMenuUpdate"
              :root-props="{
                style: 'background: transparent; border: none;'
              }" />
          </div>

          <!-- 操作区域 -->
          <div class="nav-actions">
            <!-- 侧边栏折叠按钮（仅桌面端显示） -->
            <n-button v-if="!isMobile" text size="large" @click="toggleSidebar" class="sidebar-toggle-btn"
              :title="sidebarCollapsed ? '展开侧边栏' : '折叠侧边栏'">
              <template #icon>
                <n-icon :size="24">
                  <ChevronForwardOutline v-if="sidebarCollapsed" />
                  <ChevronBackOutline v-else />
                </n-icon>
              </template>
            </n-button>

            <!-- 移动端菜单按钮 -->
            <n-button v-if="isMobile" text size="large" @click="showMobileMenu = true" class="mobile-menu-btn">
              <template #icon>
                <n-icon :size="20">
                  <MenuOutline />
                </n-icon>
              </template>
            </n-button>

            <!-- 主题切换按钮 -->
            <n-button text size="large" @click="toggleTheme" class="theme-toggle-btn"
              :title="themeStore.isDark ? '切换到浅色主题' : '切换到深色主题'">
              <template #icon>
                <n-icon :size="20">
                  <SunnyOutline v-if="themeStore.isDark" />
                  <MoonOutline v-else />
                </n-icon>
              </template>
            </n-button>

            <!-- 用户菜单 -->
            <UserMenu />
          </div>
        </nav>
      </n-layout-header>

      <n-layout-content :style="{ paddingLeft: contentPaddingLeft }">
        <router-view />
      </n-layout-content>

      <n-layout-footer bordered>
        <n-space justify="center" style="padding: 20px 24px;">
          <n-text :depth="3">
           Copyright © {{ new Date().getFullYear() }}  三角洲数据查询攻略站 | 版本 {{ latestVersion }} 备案吉icp备2025024459-1  · 使用条款&免责声明
          </n-text>
        </n-space>
      </n-layout-footer>

      <!-- 现代化移动端抽屉菜单 -->
      <n-drawer v-model:show="showMobileMenu" :width="320" placement="left" :mask-closable="true" :show-mask="true"
        :close-on-esc="true">
        <n-drawer-content title="导航菜单" :native-scrollbar="false" class="mobile-drawer">
          <template #header>
            <div class="drawer-header">
              <div class="drawer-brand">
                <n-avatar :size="32" :src="logoUrl" color="transparent">
                  <template #fallback>
                    <n-icon :size="20">
                      <HomeOutline />
                    </n-icon>
                  </template>
                </n-avatar>
                <div class="drawer-brand-text">
                  <h3>三角洲数据查询攻略站</h3>
                  <span>Operation Delta</span>
                </div>
              </div>
            </div>
          </template>

          <n-menu :value="activeKey" :options="menuOptions" @update:value="handleMobileMenuUpdate" :indent="24"
            :root-props="{
              style: 'background: transparent;'
            }" />

          <template #footer>
            <div class="drawer-footer">
              <n-button block quaternary @click="toggleTheme" size="large">
                <template #icon>
                  <n-icon>
                    <SunnyOutline v-if="themeStore.isDark" />
                    <MoonOutline v-else />
                  </n-icon>
                </template>
                {{ themeStore.isDark ? '浅色模式' : '深色模式' }}
              </n-button>
            </div>
          </template>
        </n-drawer-content>
      </n-drawer>
    </n-layout>

    <!-- 返回顶部按钮 -->
    <BackToTop />
  </n-layout>
</template>

<script lang="ts" setup>
import { ref, h, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { NIcon } from 'naive-ui'
import { useThemeStore } from '@/stores/theme'
import UserMenu from '@/components/user/UserMenu.vue'
import BackToTop from '@/components/BackToTop.vue'
import {
  HomeOutline,
  SunnyOutline,
  MoonOutline,
  MenuOutline,
  ListOutline,
  TrophyOutline,
  PeopleOutline,
  ConstructOutline,
  GitNetworkOutline,
  MapOutline,
  ShieldOutline,
  ChevronBackOutline,
  ChevronForwardOutline
} from '@vicons/ionicons5'
import logoSvg from '@/assets/logo.svg'
import updateLog from '@/views/update-log.json'
import { rankingMenuItems } from '@/config/rankingMenuConfig'

// 路由
const router = useRouter()

// 主题
const themeStore = useThemeStore()
const toggleTheme = () => {
  themeStore.toggleTheme()
}

// Logo URL - 修复路径问题
const logoUrl = ref(logoSvg)

// 移动端检测
const isMobile = ref(false)
const showMobileMenu = ref(false)

// 侧边栏折叠状态
const sidebarCollapsed = ref(false)

// 计算主内容区的左边距
const contentPaddingLeft = computed(() => {
  if (isMobile.value) return '0px'
  return sidebarCollapsed.value ? '64px' : '240px'
})

const checkMobile = () => {
  isMobile.value = window.innerWidth <= 768
}

// 从localStorage加载侧边栏折叠状态
const loadSidebarState = () => {
  const saved = localStorage.getItem('sidebarCollapsed')
  if (saved !== null) {
    sidebarCollapsed.value = JSON.parse(saved)
  }
}

// 保存侧边栏折叠状态到localStorage
const saveSidebarState = () => {
  localStorage.setItem('sidebarCollapsed', JSON.stringify(sidebarCollapsed.value))
}

// 监听侧边栏状态变化并保存
const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value
  saveSidebarState()
}

onMounted(() => {
  checkMobile()
  loadSidebarState()
  window.addEventListener('resize', checkMobile)
  if (Array.isArray(updateLog) && updateLog.length > 0) {
    latestVersion.value = updateLog[0].version || ''
  }
})

onUnmounted(() => {
  window.removeEventListener('resize', checkMobile)
})

// 菜单图标渲染函数
function renderIcon(icon: any) {
  return () => h(NIcon, null, { default: () => h(icon) })
}

// 子弹图标组件
const BulletIcon = () => h('svg', {
  viewBox: '0 0 24 24',
  fill: 'currentColor'
}, [
  h('path', {
    d: 'M12 2C13.1 2 14 2.9 14 4V8H16C17.1 8 18 8.9 18 10V20C18 21.1 17.1 22 16 22H8C6.9 22 6 21.1 6 20V10C6 8.9 6.9 8 8 8H10V4C10 2.9 10.9 2 12 2Z'
  })
])

// 渲染子弹图标
function renderBulletIcon() {
  return () => h(NIcon, null, { default: () => h(BulletIcon) })
}

// 菜单选项
const menuOptions = [
  {
    label: '首页',
    key: 'home',
    icon: renderIcon(HomeOutline)
  },
  {
    label: '物品列表',
    key: 'items',
    icon: renderIcon(ListOutline)
  },
  {
    label: '排行榜',
    key: 'ranking',
    icon: renderIcon(TrophyOutline)
  },
  {
    label: '内容创作者',
    key: 'creators',
    icon: renderIcon(PeopleOutline)
  },
  {
    label: '更新日志',
    key: 'update-log',
    icon: renderIcon(ConstructOutline)
  }
]

// 当前激活的菜单项
const activeKey = computed(() => {
  const route = router.currentRoute.value
  const routeName = route.name as string

  // 如果是排行榜页面且有type查询参数，返回对应的菜单key
  if (routeName === 'ranking' && route.query.type) {
    return `ranking?type=${route.query.type}`
  }

  return routeName || 'home'
})

// 处理菜单点击
const handleMenuUpdate = (key: string) => {
  // 处理带查询参数的路由
  if (key.includes('?')) {
    const [routeName, queryString] = key.split('?')
    const query = new URLSearchParams(queryString)
    const queryObj: Record<string, string> = {}
    query.forEach((value, key) => {
      queryObj[key] = value
    })
    router.push({ name: routeName, query: queryObj })
  } else {
    router.push({ name: key })
  }
}

// 处理移动端菜单点击
const handleMobileMenuUpdate = (key: string) => {
  // 处理带查询参数的路由
  if (key.includes('?')) {
    const [routeName, queryString] = key.split('?')
    const query = new URLSearchParams(queryString)
    const queryObj: Record<string, string> = {}
    query.forEach((value, key) => {
      queryObj[key] = value
    })
    router.push({ name: routeName, query: queryObj })
  } else {
    router.push({ name: key })
  }
  showMobileMenu.value = false
}

// 侧边菜单数据（多级菜单示例：1 2 3 级）
const sideMenuOptions = [
  {
    label: '数据中心',
    key: 'data-center',
    icon: renderIcon(ListOutline),
    children: [
      {
        label: '物品列表',
        key: 'items',
        icon: renderIcon(ListOutline)
      },
      {
        label: '综合排行榜',
        key: 'ranking-root',
        icon: renderIcon(TrophyOutline),
        children: rankingMenuItems.map(item => ({
          label: item.label,
          key: `ranking?type=${item.key}`,
          icon: typeof item.icon === 'function' ? renderBulletIcon() : renderIcon(item.icon)
        }))
      }

    ]
  },
  {
    label: '战术装备(测试有问题找群主)',
    key: 'tactical-loadouts',
    icon: renderIcon(ShieldOutline)
  },
  {
    label: '功能请求',
    key: 'feature-root',
    icon: renderIcon(ConstructOutline),
    children: [
      {
        label: '功能请求列表',
        key: 'feature-requests'
      },
      {
        label: '提交请求',
        key: 'feature-submit'
      }
    ]
  },
  {
    label: '地图菜单',
    key: 'maps-root',
    icon: renderIcon(MapOutline),
    children: [
      {
        label: '监狱地图',
        key: 'prison-map',
        icon: renderIcon(MapOutline)
      }
    ]
  },
  {
    label: '任务流程图',
    key: 'task-flowchart',
    icon: renderIcon(GitNetworkOutline)
  },
  {
    label: '内容创作者',
    key: 'creators',
    icon: renderIcon(PeopleOutline)
  }
]

// 获取最新版本号
const latestVersion = ref('')
</script>

<style scoped>
/* 基础布局 - 不添加任何颜色样式 */
.n-layout {
  min-height: 100vh;
}

/* 固定导航栏 */
.app-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background: var(--n-card-color);
  backdrop-filter: blur(8px);
  border-bottom: 1px solid var(--n-border-color);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.n-layout-content {
  padding: clamp(16px, 4vw, 32px);
  padding-top: calc(72px + clamp(16px, 4vw, 32px));
  /* 导航栏高度 + 原有padding */
  width: 100%;
}

/* 导航容器 - 只设置布局，不设置颜色 */
.nav-container {
  display: grid;
  grid-template-columns: auto 1fr auto;
  align-items: center;
  gap: clamp(16px, 4vw, 48px);
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 clamp(16px, 4vw, 32px);
  height: 72px;
}

/* 品牌区域 - 只设置布局 */
.brand-section {
  display: flex;
  align-items: center;
  gap: 16px;
  cursor: pointer;
  padding: 8px;
  border-radius: 12px;
}

.brand-logo {
  flex-shrink: 0;
}

.brand-text {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.brand-title {
  font-weight: 700;
  margin: 0;
  line-height: 1.2;
}

.brand-subtitle {
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.05em;
}

/* 导航菜单区域 */
.nav-menu {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 操作区域 */
.nav-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 侧边栏折叠按钮样式 */
.sidebar-toggle-btn {
  transition: all 0.2s ease;
  border-radius: 8px;
  padding: 8px;
}

.sidebar-toggle-btn:hover {
  transform: scale(1.1);
  background: var(--n-primary-color-hover);
}

.sidebar-toggle-btn:active {
  transform: scale(0.95);
}

/* 侧边栏基础样式与过渡动画 */
:deep(.n-layout-sider) {
  /* 使用卡片背景与主边框色，保持整体一致 */
  background: var(--n-card-color);
  border-right: 1px solid var(--n-border-color);
  /* 折叠 / 展开宽度过渡 */
  transition: width 0.2s ease;
  /* 固定在视口左侧，并避免与顶部导航重叠 */
  position: fixed;
  /* 固定定位 */
  top: 72px;
  /* 与顶部导航栏高度一致 */
  left: 0;
  height: calc(100vh - 72px);
  /* 填满除导航栏外的剩余高度 */
  overflow: auto;
  /* 菜单过多时允许滚动 */
  /* 提高层级，确保内置折叠箭头不会被其他元素遮挡 */
  z-index: 1500;
}

/* 自定义折叠触发器样式 */
:deep(.n-layout-sider .n-layout-toggle-button) {
  /* 增大触发器尺寸 */
  width: 36px !important;
  height: 36px !important;
  /* 确保触发器在最顶层 */
  z-index: 1600 !important;
  /* 增强背景和边框 */
  background: var(--n-card-color) !important;
  border: 2px solid var(--n-border-color) !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;
  /* 圆角 */
  border-radius: 50% !important;
  /* 过渡动画 */
  transition: all 0.2s ease !important;
}

:deep(.n-layout-sider .n-layout-toggle-button:hover) {
  /* 悬停效果 */
  background: var(--n-primary-color-hover) !important;
  border-color: var(--n-primary-color) !important;
  transform: scale(1.1) !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
}

/* 自定义折叠触发器图标样式 */
:deep(.n-layout-sider .n-layout-toggle-button .n-base-icon) {
  /* 增大图标尺寸 */
  font-size: 18px !important;
  color: var(--n-text-color) !important;
}

:deep(.n-layout-sider .n-layout-toggle-button:hover .n-base-icon) {
  color: var(--n-primary-color-pressed) !important;
}

/* 确保折叠触发器不被其他元素遮挡 */
:deep(.n-layout-sider .n-layout-toggle-bar) {
  z-index: 1700 !important;
  position: relative !important;
}

/* 折叠触发器容器样式 */
:deep(.n-layout-sider .n-layout-toggle-bar .n-layout-toggle-button) {
  position: relative !important;
  margin: 8px !important;
}

/* 主内容区的左边距现在通过计算属性动态设置，不需要固定的CSS规则 */
.n-layout-content {
  /* 添加过渡动画，使左边距变化更平滑 */
  transition: padding-left 0.2s ease;
}

/* 响应式设计 */
@media (max-width: 1240px) {
  .nav-container {
    max-width: 100%;
  }
}

@media (max-width: 768px) {
  .nav-container {
    height: 64px;
    gap: 16px;
    grid-template-columns: 1fr auto;
  }

  .n-layout-content {
    padding-top: calc(64px + clamp(16px, 4vw, 32px));
    /* 移动端导航栏高度 + 原有padding */
  }

  .brand-text {
    gap: 1px;
  }

  .brand-title {
    font-size: 16px;
  }

  .brand-subtitle {
    display: none;
  }
}

@media (max-width: 480px) {
  .brand-subtitle {
    display: none;
  }

  .nav-container {
    gap: 12px;
  }
}

/* 移动端抽屉菜单 - 只设置布局 */
.drawer-header {
  padding: 16px 0;
}

.drawer-brand {
  display: flex;
  align-items: center;
  gap: 12px;
}

.drawer-brand-text h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.drawer-brand-text span {
  text-transform: uppercase;
  letter-spacing: 0.05em;
}

.drawer-footer {
  padding: 16px 0;
}
</style>